<template>
  <div>
    <!-- 客户组 -->
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="qtype" style="width: 170px; margin-right: 2px;">
          <el-option value="groupCode" label="组号" />
          <el-option value="groupName" label="组名称" />
        </el-select>
        <el-input v-model.trim="txt" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="创建时间:" :table-form-merge="2" class="merge-item">
        <el-date-picker
          v-model="date"
          clearable
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
        />
      </el-form-item>
      <el-form-item label="组类型:" prop="groupType">
        <el-select v-model="query.groupType" clearable placeholder="请选择">
          <el-option
            v-for="item in groupTypeMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="状态:" prop="groupStatus">
        <el-select v-model="query.groupStatus" clearable placeholder="请选择">
          <el-option
            v-for="item in groupStatusMap"
            :key="item.value"
            :label="item.desc"
            :value="item.value"
          />
        </el-select>
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[20103,1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="[20103,2]" type="primary" icon="el-icon-circle-plus-outline" @click="addCsmGroup">新增</el-button>
        <el-button v-permission="[20103,3]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{bottomOffset:10}"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="column"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <exportDiglog ref="export" />

    <editCsmGroup ref="editCsmGroup" :group-type-map="groupTypeMap" :sub-type-all-list="subTypeAllList" />
    <relevancyCsm ref="relevancyCsm" :group-type-map="groupTypeMap" :sub-type-all-list="subTypeAllList" />
    <remark ref="remark" />
    <csmGroupDetail ref="csmGroupDetail" :csm-status-map="csmStatusMap" :group-type-map="groupTypeMap" :csm-type-map="customerTypeMap" :sub-type-all-list="subTypeAllList" />
  </div>
</template>

<script>
  import { formatColumnMap, parseTime } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import moment from 'dayjs'
  import { queryCsmGroupList, csmCancelPrint, queryExportDomain, exportCsmGroupList } from '@/api'
  import { mapGetters } from 'vuex'
  import editCsmGroup from './editCsmGroup.vue'
  import relevancyCsm from './relevancyCsm.vue'
  import remark from './Remark.vue'
  import csmGroupDetail from './csmGroupDetail.vue'

  export default {
    name: 'csm-group',
    components: {
      editCsmGroup, relevancyCsm, remark, csmGroupDetail,
      exportDiglog: require('./export.vue').default
    },
    props: {
      customerTypeMap: {
        type: Array,
        required: true
      },
      csmStatusMap: {
        type: Array,
        required: true
      },
      subTypeAllList: {
        type: Array,
        required: true
      },
      csmNewTypeMap: {
        type: Array,
        required: true
      },
      groupTypeMap: {
        type: Array,
        require: true
      },
      groupStatusMap: {
        type: Array,
        require: true
      }
    },
    data() {
      return {
        qtype: 'groupCode',
        dateType: 'createTime',
        txt: '',
        date: [],
        cardTypeAllList: [], // 客户类别枚举
        actionColWidth: 80,
        query: {
          groupType: '',
          groupStatus: ''
        },
        tableData: {
          total: 0,
          data: []
        }
      }
    },
    computed: {
      ...mapGetters([
        'userInfo', 'corpSettingData'
      ]),
      column: function() {
        const cols = [
          {
            type: 'index',
            fixed: 'left'
          },
          // {
          //   type: 'selection'
          // },
          {
            prop: 'groupCode',
            label: '客户组号',
            width: 105,
            fixed: 'left',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.opencsmGroupDetaill(row)}>{row.groupCode}</el-link>
          },
          {
            prop: 'groupType',
            label: '客户组类型',
            width: 105,
            render: (h, { row }) => <span>{ row.groupType && formatColumnMap(this.groupTypeMap, 'value', row.groupType, 'desc') }</span>
          },
          {
            prop: 'groupName',
            label: '组名称'
          },

          {
            prop: 'relationCount',
            label: '关联客户数'
          },
          {
            prop: 'createTime',
            label: '创建时间',
            width: 160,
            render: (h, { row }) => <span>{ row.createTime && parseTime(row.createTime, '{y}-{m}-{d} {h}:{i}:{s}')}</span>
          },
          {
            prop: 'groupStatus',
            label: '状态',
            width: 105,
            render: (h, { row }) => <span style={row.groupStatus === 1 ? 'color: red' : ''} >{ row.groupStatus && formatColumnMap(this.groupStatusMap, 'value', row.groupStatus, 'desc') }</span>
          },
          {
            prop: 'remark',
            label: '备注'
          },
          {
            label: '操作',
            className: 'action-col',
            width: this.actionColWidth,
            align: 'center',
            fixed: 'right',
            render: (h, { row, $index }) => {
              return (
                <div>
                  <el-dropdown>
                    <span class='el-dropdown-link'>
                      更多<i class='el-icon-arrow-down el-icon--right'></i>
                    </span>
                    <el-dropdown-menu slot='dropdown'>
                      { row.groupStatus !== 1 && (<el-dropdown-item>
                        <el-link v-permission={[20103, 4]} underline={false} size='mini' onClick={() => this.update(row, 'edit')}>
                          编辑
                        </el-link>
                      </el-dropdown-item>)}
                     {row.groupStatus === 2 && (
                      <el-dropdown-item>
                        <el-link v-permission={[20103, 5]} underline={false} size='mini' onClick={() => this.relevancyCsm(row)}>
                          关联客户
                        </el-link>
                      </el-dropdown-item>)}
                      {(
                      <el-dropdown-item>
                        <el-link v-permission={[20103, 6]} underline={false} size='mini' onClick={() => this.remark(row)}>
                          备注
                        </el-link>
                      </el-dropdown-item>)}
                    </el-dropdown-menu>
                  </el-dropdown>
                </div>
              )
            }
          }
        ]
        return cols
      }
    },
    mounted() {
    },
    methods: {
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.qtype] = this.txt
        if (this.date && this.date.length === 2) {
          query[`${this.dateType}Start`] = moment(this.date[0]).format('YYYY-MM-DD') + ' 00:00:00'
          query[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD') + ' 23:59:59'
        }
        const res = await queryCsmGroupList(query)
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
        this.getExportDomain()
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      isJsonString(str) {
        try {
          if (typeof JSON.parse(str) === 'object') {
            return true
          }
        } catch (e) {
          console.log()
        }
        return false
      },

      // 查看详情
      async opencsmGroupDetaill(row) {
        await this.$refs.csmGroupDetail.open(row)
      },
      // 新增
      async addCsmGroup() {
        await this.$refs.editCsmGroup.open()
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 编辑
      async update(row) {
        await this.$refs.editCsmGroup.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 关联客户
      async relevancyCsm(row) {
        await this.$refs.relevancyCsm.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 备注
      async remark(row) {
        await this.$refs.remark.open(row)
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },

      exportFile() {
        const query = {
          ...this._getQuery(this.query)
        }
        query[this.qtype] = this.txt
        if (this.date && this.date.length === 2) {
          query[`${this.dateType}Start`] = moment(this.date[0]).format('YYYY-MM-DD') + ' 00:00:00'
          query[`${this.dateType}End`] = moment(this.date[1]).format('YYYY-MM-DD') + ' 23:59:59'
        }
        var list = JSON.parse(JSON.stringify(this.column))
        list.pop()
        list.shift()
        const value = {}
        list.forEach(l => {
          value[l.prop] = l.label
          return value
        })
        exportCsmGroupList({
          paramInfo: query,
          kv: value // 表格列
        }).then((res) => {
          window.open(`${this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
        })
      },
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
            console.log('this.exportDomain', this.exportDomain)
          })
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      upDataTable() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 60
        })
      },

      async tryPrint(row) {
        const { status, data } = await csmCancelPrint({ csmId: row.csmId })
        if (status === 200) {
          this.print(row, data)
        }
      },
      print(row2, resdata) {
        const row = JSON.parse(JSON.stringify(row2))
        const cache = JSON.parse(localStorage.tp)
        if (!cache) {
          this.$message.warning('请先设置打印模板')
          return
        }
        const temp = cache['31']
        if (!temp) {
          this.$message.warning('请先设置打印模板')
          return
        }
        if (row.cancelTime) {
          row.cancelDt = parseTime(row.cancelTime, '{y}-{m}-{d} {h}:{i}:{s}')
        } else {
          row.cancelDt = parseTime(new Date(), '{y}-{m}-{d} {h}:{i}:{s}')
        }
        row.csmAddress = row.csmRgAddress.replace(
          /([\u4E00-\u9FA5]*)([省市])(\s*)([\u4E00-\u9FA5]*)市/g,
          ''
        )
        let printcmd = {
          cmd: 2,
          title: `正在对销户单${row.csmCode}进行配送单打印`,
          elements: []
        }
        printcmd = { ...printcmd, ...temp }
        if (!window.jCPrint || !window.jCPrint.ws) {
          this.$message.error('打印未连接')
          return
        }
        window.jCPrint.process(printcmd, temp, row, resdata)
        if (window.jCPrint.firePush(JSON.stringify(printcmd))) {
          this.$message.success('打印指令已发送')
        } else {
          this.$message.error('打印未连接')
        }
      }
    }
  }
</script>

<style lang="scss" scoped>
</style>
